package com.shoujifeng.snowmusic.player;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.entity.Mp3Info;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.utils.MediaUtil;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;
import com.shoujifeng.snowmusic.player.utils.ViewHolder;

/**
 * 编辑音乐
 * 
 * @author luo
 * 
 */
public class EditListMusicActivty extends Activity {
	private ListView contactsDelList;
	private List<Mp3Info> mp3Infos;
	private MyAdapter adapter;
	private ArrayList<Object> listStr = null;
	public static List<HashMap<String, Object>> mp3list ;
	private View lineLay;
	private Button selectAllBtn;
	private boolean selectAll = false;
	private RelativeLayout headView;
	private TextView headText;
	private ImageButton breakBtn;
	private Button deleteMusic;
	public static  List<String> noList;
	private Button addToMenu;
	private static String sdState = Environment.getExternalStorageState();
	private static String path = Environment.getExternalStorageDirectory()
			.toString();
	
	private View mDelLayView;
	private Button mDelOnButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_list_music);
		init();

		if(getIntent().getExtras().get("activityName")
				.equals("Downloadding"))
		{
			mDelLayView.setVisibility(View.VISIBLE);
		}
	}

	private void init() {
		contactsDelList = (ListView) findViewById(R.id.contacts_delete_list);
		contactsDelList.setDivider(null);
		lineLay = LayoutInflater.from(EditListMusicActivty.this).inflate(
				R.layout.line_layout, null);
		contactsDelList.addFooterView(lineLay);
		// addMenuBtn = (Button) findViewById(R.id.add_menu_btn);
		selectAllBtn = (Button) findViewById(R.id.select_all_btn);
		headView = (RelativeLayout) findViewById(R.id.headLay);
		headText = (TextView) headView.findViewById(R.id.head_text);
		headText.setText("编辑本地音乐");
		breakBtn = (ImageButton) headView.findViewById(R.id.breakBtn);
		deleteMusic = (Button) findViewById(R.id.deleteMusic);
		addToMenu = (Button) findViewById(R.id.addToMenu);
		mDelLayView = (View) findViewById(R.id.edit_del_lay);
		mDelOnButton = (Button) findViewById(R.id.deletebtn);

		showCheckBoxListView();
		selectAllBtn.setOnClickListener(onClickListener);
		breakBtn.setOnClickListener(onClickListener);
		deleteMusic.setOnClickListener(onClickListener);
		addToMenu.setOnClickListener(onClickListener);
		mDelOnButton.setOnClickListener(onDownDelListener);
	}

	private View.OnClickListener onDownDelListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if(getIntent().getExtras().get("activityName")
					.equals("Downloadding"))
			{
				for (int i = 0; i < noList.size(); i++) {
					int no = Integer.parseInt(noList
							.get(i));
					
					GlobalValue.g_DownloadManager.deleteDown(no);
				}
				
				Toast.makeText(EditListMusicActivty.this, "删除成功!", Toast.LENGTH_SHORT).show();
				
				finish();
			}
		}
	};
	
	// 删除选中的歌曲
	private View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.deleteMusic: {
				
				
				if(getIntent().getExtras().get("activityName")
						.equals("DownLoadOverActivity"))
				{
					// 删除数据库的中数据
					DatabaseUtil databaseUtil = new DatabaseUtil(EditListMusicActivty.this);
					
					for (int i = 0; i < noList.size(); i++) {
						
						HashMap<String, Object> map =  mp3list.get(Integer.valueOf(noList.get(i)));
						String url = map.get("url").toString();
						File file = new File(url);
						
						int uid = Integer.parseInt(map.get("index").toString());
						if (sdState.equals(Environment.MEDIA_MOUNTED)) {
							databaseUtil.deleteDown(uid);
							
							if (file.exists()) {
								if (file.isFile()) {
									file.delete(); // 删除歌曲
								}
							}
						}
					}
				}
				else {
					for (int i = 0; i < noList.size(); i++) {
						String url = mp3list
								.get(Integer.valueOf(noList.get(i)))
								.get("url").toString();
						File file = new File(url);
						if (sdState.equals(Environment.MEDIA_MOUNTED)) {
							
									// 删除数据库的中数据
									DatabaseUtil databaseUtil = new DatabaseUtil(EditListMusicActivty.this);
									EditListMusicActivty.this
											.getContentResolver()
											.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
													"_data = ?",
													new String[] { url });
									databaseUtil.deleteMusic(url);
									if (file.exists()) {
										if (file.isFile()) {
									file.delete(); // 删除歌曲
									int no = Integer.parseInt(noList
											.get(i));
									mp3list.remove(no); // 删除列表中的数据
									mp3Infos.remove(no);
									
									MusicPlayer.musicInfos = mp3Infos;
									if (getIntent().getExtras().get("activityName")
											.equals("MusicByPlayerActivity")) {
										
										MusicByPlayerActivity.mp3list.remove(no);
										MusicByPlayerActivity.mp3list =mp3list;
									}
									if (getIntent().getExtras().get("activityName")
											.equals("MusicBySpecialActivity")) {
										MusicByPlayerActivity.mp3list.remove(no);
										MusicBySpecialActivity.mp3list = mp3list;
									}

									if (getIntent().getExtras().get("activityName")
											.equals("NativeMusicActivity")
											) {
										NativeMusicActivity.mp3list = mp3list;
									}
								}
							}
						}
					}
				}
				
				
				showCheckBoxListView();
				//adapter.notifyDataSetChanged();
				Toast.makeText(EditListMusicActivty.this, "删除成功",
						Toast.LENGTH_SHORT).show();
				
				finish();
			}
				break;
			case R.id.addToMenu: {
				if(noList.size()==0){
					Toast.makeText(EditListMusicActivty.this, "请先选择歌曲",
							Toast.LENGTH_SHORT).show();
				}
				else{
					Intent intent = new Intent(EditListMusicActivty.this,EditAddTo.class);
					startActivity(intent);
					
					finish();
				}
				
			}
				break;
			case R.id.breakBtn: {
				finish();
			}
				break;
			case R.id.select_all_btn: {

				if (selectAll == false) {
					selectAll = true;
					selectAllBtn
							.setBackgroundResource(R.drawable.select_all_yes_bg);
				} else {
					selectAll = false;
					selectAllBtn
							.setBackgroundResource(R.drawable.select_all_bgl);
				}

				for (int i = 0; i < mp3Infos.size(); i++) {
					if (MyAdapter.isSelected.get(i) == false) {
						MyAdapter.isSelected.put(i, true);
						listStr.add(mp3Infos.get(i).getTitle());
						noList.add(i + "");
					} else {
						MyAdapter.isSelected.put(i, false);
						listStr.remove(mp3Infos.get(i).getTitle());
						noList.remove(i + "");
					}
				}

				adapter.notifyDataSetChanged();
			}

				break;

			default:
				break;
			}
		}
	};

	// 显示带有checkbox的listview
	public void showCheckBoxListView() {

		if (getIntent().getExtras().get("activityName")
				.equals("MusicByPlayerActivity")) {
			mp3Infos = MusicByPlayerActivity.mp3Infos;
			MusicPlayer.musicInfos = new ArrayList<Mp3Info>();
			MusicPlayer.musicInfos = mp3Infos;
			mp3list = new ArrayList<HashMap<String, Object>>();
			mp3list = MusicByPlayerActivity.mp3list;
		}else if (getIntent().getExtras().get("activityName")
				.equals("MusicBySpecialActivity")) {
			mp3Infos = MusicBySpecialActivity.mp3Infos;
			MusicPlayer.musicInfos = new ArrayList<Mp3Info>();
			MusicPlayer.musicInfos = mp3Infos;
			mp3list = new ArrayList<HashMap<String, Object>>();
			mp3list = MusicBySpecialActivity.mp3list;
		}
		else if(getIntent().getExtras().get("activityName")
				.equals("DownLoadOverActivity")) {
			
			mp3Infos = MusicPlayer.musicInfos;
			mp3list = new ArrayList<HashMap<String, Object>>();
			for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {
				Mp3Info mp3Info = (Mp3Info) iterator.next();
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("title", mp3Info.getTitle());
				map.put("Artist", mp3Info.getArtist());
				map.put("duration", String.valueOf(mp3Info.getDuration()));
				map.put("size", String.valueOf(mp3Info.getSize()));
				map.put("url", mp3Info.getUrl());
				map.put("index", mp3Info.getId());
				mp3list.add(map);
			}
			
		}else if(getIntent().getExtras().get("activityName")
				.equals("Downloadding"))  {
			mp3Infos = MusicPlayer.musicInfos;
			mp3list = new ArrayList<HashMap<String, Object>>();
			for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {
				Mp3Info mp3Info = (Mp3Info) iterator.next();
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("title", mp3Info.getTitle());
				map.put("Artist", mp3Info.getArtist());
				map.put("duration", 0);
				map.put("size",0);
				map.put("index",mp3Info.getId());
				map.put("url", mp3Info.getUrl());
				mp3list.add(map);
			}
		}
		else if (getIntent().getExtras().get("activityName")
				.equals("NativeMusicActivity")
				) {
			MediaUtil mediaUtil = new MediaUtil();
			mp3Infos = mediaUtil.getMp3Infos(EditListMusicActivty.this);
			MusicPlayer.musicInfos = new ArrayList<Mp3Info>();
			MusicPlayer.musicInfos = mp3Infos;
			mp3list = new ArrayList<HashMap<String, Object>>();
			for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {
				Mp3Info mp3Info = (Mp3Info) iterator.next();
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("title", mp3Info.getTitle());
				map.put("Artist", mp3Info.getArtist());
				map.put("duration", String.valueOf(mp3Info.getDuration()));
				map.put("size", String.valueOf(mp3Info.getSize()));
				map.put("url", mp3Info.getUrl());
				mp3list.add(map);
			}
		}
		adapter = new MyAdapter(this, mp3list, R.layout.add_to_menu_list,
				new String[] { "title", "Artist" }, new int[] { R.id.musicname,
						R.id.playername });
		contactsDelList.setAdapter(adapter);

		listStr = new ArrayList<Object>();
		noList = new ArrayList<String>();
		contactsDelList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				ViewHolder holder = (ViewHolder) view.getTag();
				holder.checkBox.toggle();// 在每次获取点击的item时改变checkbox的状态
				MyAdapter.isSelected.put(position, holder.checkBox.isChecked()); // 同时修改map的值保存状态
				if (holder.checkBox.isChecked() == true) {
					listStr.add(mp3list.get(position).get("title"));
					noList.add(position + "");
				} else {
					listStr.remove(mp3list.get(position).get("title"));
					noList.remove(position + "");
				}
			}

		});
	}

	// 为listview自定义适配器内部类
	public static class MyAdapter extends BaseAdapter {
		public static HashMap<Integer, Boolean> isSelected;
		
		private Context context = null;
		private LayoutInflater inflater = null;
		private List<HashMap<String, Object>> list = null;
		private String keyString[] = null;
		private String itemString = null; // 记录每个item中textview的值
		private int idValue[] = null;// id值

		public MyAdapter(Context context, List<HashMap<String, Object>> list,
				int resource, String[] from, int[] to) {
			this.context = context;
			this.list = list;
			keyString = new String[from.length];
			idValue = new int[to.length];
			System.arraycopy(from, 0, keyString, 0, from.length);
			System.arraycopy(to, 0, idValue, 0, to.length);
			inflater = LayoutInflater.from(context);
			init();
		}

		// 初始化 设置所有checkbox都为未选择
		public void init() {
			isSelected = new HashMap<Integer, Boolean>();
			noList = new ArrayList<String>();
			for (int i = 0; i < list.size(); i++) {
				isSelected.put(i, false);
			}
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View view, ViewGroup arg2) {
			ViewHolder holder = null;
			if (holder == null) {
				holder = new ViewHolder();
				if (view == null) {
					view = inflater.inflate(R.layout.add_to_menu_list, null);
				}
				holder.musicnameView = (TextView) view
						.findViewById(R.id.musicname);
				holder.playernameView = (TextView) view
						.findViewById(R.id.playername);
				holder.checkBox = (CheckBox) view
						.findViewById(R.id.delete_list_item);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}
			HashMap<String, Object> map = list.get(position);
			if (map != null) {
				itemString = (String) map.get(keyString[0]);
				holder.musicnameView.setText(itemString);
				holder.playernameView.setText(list.get(position).get("Artist")
						.toString());
			}
			holder.checkBox.setChecked(isSelected.get(position));
			return view;
		}
	}

}